package com.lxhll.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxhll.personnel.dao.DepartmentDao;
import com.lxhll.personnel.entity.Department;
import com.lxhll.personnel.entity.Employee;
import com.lxhll.personnel.service.DepartmentService;
import com.lxhll.personnel.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentDao,Department> implements DepartmentService {
    @Autowired
    private EmployeeService employeeService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 增加部门，并存入redis
     * @param id
     * @return
     */
    @Override
    public Department getDepartmentById(Integer id) {
        Object department=redisTemplate.opsForValue().get("department_"+id);
        if (department == null) {
            department = this.baseMapper.selectById(id);
            redisTemplate.opsForValue().set("department_" + id, department, 1, TimeUnit.HOURS);
        }
        return (Department)department;
    }

    /**
     * 统计各部门人数
     * @return
     */
    @Override
    public List<Map<String, Object>> statisticsEmployeeNumber() {
        return this.baseMapper.statisticsEmployeeNumber();
    }

    /**
     * 统计人事月报
     * @param date
     * @return
     */
    @Override
    public List<Map<String, Object>> statisticsDetails(String date) {
        return this.baseMapper.statisticsDetails(date);
    }





    /**
     * 如果该部门下有员工，则不能删除，并回滚。删除时顺带删除redis
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeDepartmentByIds(Integer[] ids) {
        //如果部门下有员工，则不能删除部门
        for(int id:ids){
            if(employeeService.count(new QueryWrapper<Employee>().eq("department_id",id))!=0){
                return false;
            }
        }
        this.removeByIds(Arrays.asList(ids));
        for(int id:ids){
            redisTemplate.delete("department_"+id);
        }
        return true;
    }


    /**
     * 更新部门，顺带更新redis
     * @param department
     * @return
     */
    @Override
    public boolean updateDepartmentById(Department department) {
        department.setModifyDate(LocalDate.now());
        this.updateById(department);
        redisTemplate.opsForValue().set("department_"+department.getId(),department,1,TimeUnit.HOURS);
        return true;
    }






}
